<template>
  <div id="container">
    <div id="image">
      <img src="../assets/1.png">
    </div>
    <el-form id="form" ref="ruleFormRef" :rules="rules" status-icon :model="pageVar.UserInfo">
      <h1>食必达用户登录</h1>
      <el-form-item prop="user_name">
        <el-input v-model="pageVar.UserInfo.userName" prefix-icon="Avatar" placeholder="请输入用户名"/>
      </el-form-item>
      <el-form-item prop="pwd">
        <el-input v-model="pageVar.UserInfo.pwd" type="password" autocomplete="off" prefix-icon="Unlock"
                  placeholder="请输入密码" @keyup.enter="match($router)"/>
      </el-form-item>
      <el-link type="primary" @click="register">没有账号请先注册？</el-link>
      <div id="commit" router>
        <el-button type="primary" plain @click="register">注册</el-button>
        <el-button type="success" plain style="margin-left: 70px" @click="match($router)">登录</el-button>
      </div>
    </el-form>

    <!--    注册界面-->
    <el-dialog v-model="visible" title="用户注册">
      <el-form ref="ruleFormRef" :rules="rules" status-icon :model="pageVar.UserInfo">
        <el-form-item prop="user-name">
          <el-input v-model="pageVar.UserInfo.userName" prefix-icon="Avatar" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item prop="pwd">
          <el-input v-model="pageVar.UserInfo.pwd" autocomplete="off" prefix-icon="Unlock" placeholder="请输入密码"
                    type="password"/>
        </el-form-item>
        <el-form-item prop="cpwd">
          <el-input v-model="pageVar.UserInfo.cpwd" autocomplete="off" prefix-icon="Unlock" placeholder="请输入密码"
                    type="password"/>
        </el-form-item>
        <div style="text-align: center;">
          <el-button @click="resetInfo">重置</el-button>
          <el-button type="success" plain style="margin-left: 70px" @click="Register">注册</el-button>
        </div>
      </el-form>

    </el-dialog>
  </div>
</template>

<script setup>
import {getCurrentInstance, reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import router from "../components/router"
import {FormRules} from 'element-plus'
import {FormInstance} from "element-plus";
let pageVar = reactive({
      visible: false, // 对话框的显示与隐藏状态,
      UserInfo: {
        userName: '', // 登录页：用户名输入框对应的数据属性
        pwd: '', // 登录页：密码输入框对应的数据属性
        cpwd: '',//校验密码
      },
    }
)
let {proxy} = getCurrentInstance()
//校验规则失效，采取备用方法
//登录处理
const match = (router) => {
  const usernameRegex = /^[a-zA-Z0-9_-]{4,16}$/;
  if(usernameRegex.test(pageVar.UserInfo.userName)){
  proxy.$axios.post(`${proxy.serCtx}/userBase/login`, pageVar.UserInfo).then((res) => {
    if (pageVar.UserInfo.pwd === res.data.pwd) {
      //获取用户名和用户id存到浏览器缓存
      localStorage.setItem("name",JSON.stringify(res.data.userName))
      localStorage.setItem("id",JSON.stringify(res.data.id))
      //使用localStorge数据
      proxy.$currentUser.name=JSON.parse(localStorage.getItem('name'))
      proxy.$currentUser.id=JSON.parse(localStorage.getItem('id'))
      proxy.$isLogin.value=true
      router.push('/mainPage')
    } else {
      ElMessage("密码不通过");
    }
  }).catch((err) => {
    console.log(err)
  })
}else{
    ElMessage("用户名不符合规范")
  }

}

//注册
let visible = ref(false)

const Register = () => {
  const usernameRegex = /^[a-zA-Z0-9_-]{4,16}$/;
  if(usernameRegex.test(pageVar.UserInfo.userName)){
  if (pageVar.UserInfo.pwd === pageVar.UserInfo.cpwd) {
    proxy.$axios.post(`${proxy.serCtx}/userBase/register`, pageVar.UserInfo).then((res) => {
      if (res.data == true) {
        ElMessage("注册成功！")
        visible.value = false
      } else {
        ElMessage("用户存在，注册失败")
      }
    }).catch((err) => {
      console.log(err)
    })
  }else{
    ElMessage("两次密码不一致")
  }}else{
    ElMessage("用户名不符合规范")
  }
}




  function register() {
    visible.value = true
  }

  function resetInfo() {
    pageVar.UserInfo.userName = ''
    pageVar.UserInfo.pwd = ''
    pageVar.UserInfo.cpwd = ''
  }



  //校验规则
  const ruleFormRef = ref<FormInstance>(null)

  const checkUsername = (rule, value, callback) => {
    if (!value) {
      return callback(new Error('请填写用户名'));
    }
    // 自定义用户名合规规则的正则表达式
    const usernameRegex = /^[a-zA-Z0-9_-]{4,16}$/;

    if (!usernameRegex.test(value)) {
      callback(new Error('用户名必须是 4 到 16 个字符，可以包含字母、数字、下划线和短横线'));
    } else {
      callback();
    }
  };
  const validatePass = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('Please input the password'))
    } else {
      if (pageVar.UserInfo.cpwd !== '') {
        if (!ruleFormRef.value) return
        ruleFormRef.value.validateField('checkPass', () => null)
      }
      callback()
    }
  }
  const validatePass2 = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('Please input the password again'))
    } else if (value !== pageVar.UserInfo.pwd) {
      callback(new Error("Two inputs don't match!"))
    } else {
      callback()
    }
  }
  const rules = reactive<FormRules<typeof pageVar.UserInfo>>({
    user_name: [{validator: validatePass, trigger: 'blur'}],
    pwd: [{validator: validatePass2, trigger: 'blur'}],
    cpwd: [{validator: checkUsername, trigger: 'blur'}],
  })


// 路由导航守卫
  router.beforeEach((to, from, next) => {
    const requiresAuth = to.meta.requiresAuth;

    if (requiresAuth && !isLogged()) {
      // 如果需要登录且未登录，则重定向到登录页
      next("/loginPage");
    } else {
      // 允许访问其他页面
      next();
    }
  });

// 模拟登录状态（请根据你的实际情况进行修改）
function isLogged() {
  return proxy.$isLogin.value; // 假设使用了一个名为 $isLogin 的响应式数据
}

</script>

<style scoped>
h1 {
  background: linear-gradient(to right, lightblue, darkcyan);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

body, html {
  height: 100%;
  margin: 0;
}

#container {
  width: 70vw;
  height: 55vh;
  border: #2c3e50 solid 1px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  justify-content: center;
  align-items: center;
}

#image {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  display: inline-block;
}

#image > img {
  width: 30vw;
  height: 54vh;
}

#form {
  flex: 1;
  padding: 15px;
}

#form > h1 {
  text-align: center;
}

#commit {
  padding-top: 30px;
  display: flex;
  justify-content: center;
}

#commit > el-button {

  float: right;
}


</style>

